﻿using System;
using System.Configuration;
using ErrorDumper.Filtering;

namespace ErrorDumper.Configuration {
    public class FilterElement : ConfigurationElementCollection {
        public FilterElement() {
            AddElementName = "property";
        }

        [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
        public string Name {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("mode", IsRequired = false)]
        public ExceptionHandlingLevel? Mode {
            get { return (ExceptionHandlingLevel?)this["mode"]; }
            set { this["mode"] = value; }
        }

        protected override ConfigurationElement CreateNewElement() {
            return new FilterPropertyElement();
        }

        protected override object GetElementKey(ConfigurationElement element) {
            return ((FilterPropertyElement)element).Name;
        }

        public FilterPropertyElement GetPropertyName(string propertyName) {
            return (FilterPropertyElement)BaseGet(propertyName);
        }

        public bool IsMatch(ExceptionPropertyCollection properties) {
            if (properties == null)
                throw new ArgumentNullException("properties");

            foreach (FilterPropertyElement property in this) {
                object _value = properties[property.Name];
                if (_value == null)
                    return false;
                if (property.Count == 0)
                    continue;

                string __value;
                if (_value is string)
                    __value = (string)_value;
                else if (_value is DateTime)
                    __value = ((DateTime)_value).ToString("s");
                else
                    __value = _value.ToString();

                if (!property.ContainsValue(__value))
                    return false;
            }

            return true;
        }
    }
}